<template>
  <view>
    <view id="top" ref="top" class="tops">
	    <u-picker :show="showUPicker" ref="uPicker" :columns="cityList" @confirm="confirm" @change="changeHandler" @cancel="show = false"></u-picker>
      <l-tab-bar type="3" :tabs="tabs" :active-inx.sync="activeInx" @change="tabClick" />
    </view>
    <swiper
        class="bg-primary"
        :style="{height:scrollHeight + 110 +'px'}"
        :current="activeInx"
        :duration="300"
        @change="onswiperchange"
        @animationfinish="animationfinish"
        @onAnimationEnd="animationfinish"
    >
      <swiper-item v-for="(page, index) in tabs" :key="index" class="flex-column">
		  <view class="driver" style="width: 100vw; height: 1rpx; background-color: transparent;margin-top:190rpx;"></view>
        <order-page :orderType="3" :isPickup="3" ref="page" class="flex-column flex-item" 
		:current="current" 
		:height="scrollHeight" 
		:type="page.type" 
		@showModel="showModel" 
		@getSize="getSize" 
		/>
      </swiper-item>
    </swiper>

    <l-add-button @click="jump('/order/add-new/add-new?pType=3')" />

    <!-- #ifndef APP-PLUS -->
    <order-modal :person="person" :show.sync="show" @reload="reload(activeInx)" />
    <!-- #endif -->

    <view v-if="noPermission" class="no-permission">
      <l-no-data type="permission" text="暂无权限" />
    </view>
  </view>
</template>

<script>
import OrderPage from '../order-page/order-page'
import OrderModal from '../order-modal/order-modal'
import request from '@/common/api/request'
import colors from '@/common/colors'
import { mapGetters, mapMutations } from 'vuex'
import { jump, getElementInfo, sysInfo } from '@/common/util'
import { getNewestVerion } from '@/common/api/version'
import { checkVersion, openSubView } from '@/common/plus'
import cityData from '@/common/area.json'
// #ifdef APP-PLUS
const dom = weex.requireModule('dom')
// #endif
let pageList = []
const MAX_CACHE_DATA = 20
export default {
  components: {
    OrderPage,
    OrderModal
  },
  data() {
    return {
		shoDatetime:false,
		list: [
				{
					name: '旅游包车'
				}, 
				{
					name: '商务接送'
				}, 
				{
					name: '特价巴士'
			}
			],
			person:{},
		current: 0,
		cityList: [],
		cityLevel1: [],
		cityLevel2: [],
		cityLevel3: [],
      activeInx: 0,
      tabs: [
        { title: '待完成', size: 0, type: 0, icon: 'icon_order_finish.png' },
        { title: '待确认', size: 0, type: 1, icon: 'icon_order_confirm.png' },
        { title: '已结束', size: 0, type: 2, icon: 'icon_order_end.png' }
      ],
      scrollHeight: 0,
      isTap: false,
      _lastTabIndex: 0,
      show: false,
	  showUPicker:false,
	  showData:false,
      noPermission: false,
      colorT1: colors.fontcolorT1,
	  chooseCity:['海南省','海口市'],
	  single: "2021-04-3",
	  typeofJudge:3
    }
  },
  computed: {
    ...mapGetters({
      userInfo: 'userInfo',
      userId: 'userId',
      auth: 'auth',
      orderIndex: 'orderIndex',
      firstLogin: 'firstLogin',
      firstShowModel: 'firstShowModel'
    })
  },
  onLoad() {
  	this.initCityData()
  },
  onShow() {
    /* #ifdef MP-WEIXIN*/
    if (this.firstLogin) {
      this.showWechatModal(0)
    }
    /* #endif*/
    if (this.userId) {
      this.noPermission = !this.auth.includes('travel_order_view')
      if (pageList.length) {
        for (let i = 0; i < pageList.length; i++) {
          this.reload(i)
        }
        if (this.orderIndex === 0) {
          this.switchTab(0)
          this.setOrderIndex(null)
        }
      }
    }
  },
  beforeCreate() {
    // #ifdef APP-PLUS
    dom.addRule('fontFace', {
      'fontFamily': 'tbbAdminApp',
      'src': "url('https://at.alicdn.com/t/font_3339163_kolu475jyt.ttf?t=1650889807885')"
    })
    // #endif
  },
  onPullDownRefresh() {
    if (this.activeInx === 0) pageList[this.activeInx].getData()
    else pageList[this.activeInx].reloadList()
  },
  mounted() {
    this.getPageHeight()
    this.checkNewestVersion()
    uni.$on('orderReload', () => {
      this.reload(this.activeInx)
    })
	setTimeout(() => {
		const currentDate = new Date();
		  const year = currentDate.getFullYear();
		  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
		  const day = String(currentDate.getDate()).padStart(2, '0');
		  const dateNumericFormat = year + '-' + month + '-' + day
		  console.log(dateNumericFormat) 
		  this.single = dateNumericFormat;
	}, 1000);
  },
  beforeDestroy() {
    uni.$off('orderReload')
  },
  methods: { 
	  	shoDatetimeChange(e) {
	  				this.single = e;
	  				console.log("-change事件:", e);
	  			},
	  screeningDownCityFn(){
		this.showUPicker = true  
	  },
	  initCityData(){
                // 遍历城市
				cityData.forEach((item1, index1) =>{
					let temp2 = [];
					this.cityLevel1.push(item1.label);
					
					let temp4 = [];
					let temp3 = [];
					// // 遍历市
					item1.children.forEach((item2, index2) =>{
						temp2.push(item2.label);
						// 遍历区
						// if(item2.children && item2.children.length > 0){
						// 	item2.children.forEach((item3, index3) =>{
						// 		temp3.push(item3.label);
						// 	})
						// }
						temp4[index2] = temp3;
						temp3 = [];
					})
					// this.cityLevel3[index1] = temp4;
					
					this.cityLevel2[index1] = temp2;
				})
				// 选择器默认城市
				// this.cityList.push(this.cityLevel1,this.cityLevel2[0],this.cityLevel3[0][0]);
				this.cityList.push(this.cityLevel1,this.cityLevel2[0]);
			},
			  changeHandler(e) {
							const {
								columnIndex,
								index,
								indexs,
								value,
								values,
								// 微信小程序无法将picker实例传出来，只能通过ref操作
								picker = this.$refs.uPicker
							} = e;
							if (columnIndex === 0) { // 选择第一列数据时
			                    // 设置第二列关联数据
								picker.setColumnValues(1, this.cityLevel2[index]);
			                    // 设置第三列关联数据
								// picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
							}else if(columnIndex === 1){// 选择第二列数据时
			                    // 设置第三列关联数据
								// picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
							}
						},
						confirm(e) {
							// 输出数组 [省, 市, 区]
							this.chooseCity = e.value
							console.log(e.value);
							// 隐藏城市选择器
							this.showUPicker = false;
							},
	  sectionChange(index) {
	  				this.current = index;
					if(index == 2){
						this.tabs =[
							{ title: '待抢单', size: 0, type: 3, icon: 'icon_order_end.png' },
							{ title: '待支付', size: 0, type: 4, icon: 'icon_order_end.png' },
							{ title: '待完成', size: 0, type: 0, icon: 'icon_order_finish.png' },
							{ title: '已结束', size: 0, type: 2, icon: 'icon_order_end.png' }
									]
					}else{
						this.tabs =[
							{ title: '待完成', size: 0, type: 0, icon: 'icon_order_finish.png' },
							{ title: '待确认', size: 0, type: 1, icon: 'icon_order_confirm.png' },
							{ title: '已结束', size: 0, type: 2, icon: 'icon_order_end.png' }
									]
					}
	  			},
    jump,
    async checkNewestVersion() {
      /* #ifdef APP-PLUS*/
      const [err, res] = await getNewestVerion({ platform: 2 })
      if (!request.errorCheck(err, res)) return false
      const data = res.data.data
      if (data) {
        checkVersion(data).then((res) => {
          if (res) {
            openSubView('/components/update-modal/update-modal', 'zoom-fade-out', 11, 'upload-mask')
            uni.$on('cancelUpdate', () => {
              this.init()
            })
          } else {
            this.init()
          }
        })
      } else {
        /* #endif*/
        this.init()
        /* #ifdef APP-PLUS*/
      }
      /* #endif*/
    },
    init() {
      pageList = this.$refs.page
      this.switchTab(1)
      this.switchTab(0)
    },
    // 获取滚动部分高度
    getPageHeight() {
      setTimeout(() => {
      //   getElementInfo('#top', res => {
      //     const windowHeight = sysInfo().windowHeight
      //     this.scrollHeight = windowHeight - res.height
      //   }, this)
	  getElementInfo('.driver', res => {
	  if (res && res.length > 0) {
	  	const windowHeight = sysInfo().windowHeight
	  	this.scrollHeight = windowHeight - res[0].top
	  	// this.marginTop = res.height + 20
	  }
	  }, this)
      }, 200)
    },
    reload(index) {
      if (index) pageList[index].reloadList()
      else pageList[index].getData()
    },
    tabClick(cur) {
      // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
      this.isTap = true
      // #endif
      this.switchTab(cur)
      // if (this.firstShowModel && cur === 1) {
        // this.showWechatModal(1)
        // this.setFirstShowModel(false)
      // }
    },
    switchTab(index) {
      if (pageList[index].list.length === 0) {
        if (index) pageList[index].reloadList()
        else pageList[index].getData()
      }

      if (this.activeInx === index) {
        return
      }

      /* #ifdef MP*/
      if (pageList[this.activeInx].list.length > MAX_CACHE_DATA) {
        pageList[this.activeInx].clear()
      }
      /* #endif*/

      this.activeInx = index
    },
    /* swiper*/
    onswiperchange(e) {
      const index = e.target.current || e.detail.current
      // #ifndef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
      this.switchTab(index)
      // #endif
      if (this.firstShowModel && index === 1) {
        this.showWechatModal(1)
        this.setFirstShowModel(false)
      }
    },
    animationfinish(e) {
      // #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
      const index = e.detail.current
      if (this.activeInx === index) {
        this.isTap = false
      }
      this._lastTabIndex = index
      this.switchTab(index)
      // #endif
    },
    /* swiper end*/

    // 显示弹窗
    showModel(e) {
      let options = {
        type: 0,
        id: e.id,
        payWay: e.payWay,
        status: e.status,
        title: '提示',
        content: '结束行程后将不可撤销，是否确定结束行程',
        button: [
          {
            text: '取消',
            type: 'gray'
          },
          {
            text: '确定'
          }
        ]
      }
      if (e.type === 'confirmOrder') {
        options = {
          type: 1,
          id: e.id,
          title: '确认订单',
          content: '确认订单后将通知司机和客户，请确保司机和车辆能够为客户提供服务。',
          button: [
            {
              text: '取消',
              type: 'gray'
            },
            {
              text: '确认订单'
            }
          ]
        }
      }
	  this.person = options
      /* #ifndef APP-NVUE*/
      // uni.$emit('orderShowModal', options)
      this.show = true
      /* #endif*/

      /* #ifdef APP-NVUE*/
      openSubView('/pages/order/components/order-modal/order-modal', 'zoom-fade-out', 11, 'order-mask')
      setTimeout(() => {
        // uni.$emit('orderShowModal', options)
      }, 100)
      /* #endif*/
    },
    getSize(e) {
      this.tabs[e.type].size = e.size
    },
    showWechatModal(type) {
      const options = {
        type: 999,
        modalType: type,
        title: '提示',
        content: '订单提醒功能需要获取微信消息通知权限',
        button: [
          {
            text: '确定'
          }
        ]
      }
	  this.person = options
      // uni.$emit('orderShowModal', options)
      this.show = true
      this.setFirstLogin(false)
    },
    ...mapMutations({
      setOrderIndex: 'order/setOrderIndex',
      setFirstLogin: 'status/setFirstLogin',
      setFirstShowModel: 'status/setFirstShowModel'
    })
  }
}
</script>

<style scoped lang="scss">
.tops {
	position: fixed;
	z-index: 99;
}
.no-permission{
  @include position(fixed,0,0,0,0);
  background:$color-background;
}
/deep/ .u-subsection--subsection{
	height: 90rpx !important;
}
/deep/ .u-subsection__item__text{
	font-size: 30rpx !important;
	font-weight: 400 !important;
}
/deep/ .u-subsection__item--no-border-right,/deep/ .u-subsection__item--last{
	border: none !important;
}
// 筛选
.screening{
	width: 100%;
	box-sizing: border-box;
	padding:0rpx 30rpx 30rpx;
	font-size: 30rpx;
	font-weight: 400;
	display: flex;
	justify-content: space-between;
	align-items: center;
	flex-direction: row !important;
	.screening-city{
		width: fit-content;
		flex-direction: row !important;
		align-items: center;
		.screening-down-city{
			width: 20rpx;
			height: 20rpx;
			border-top: 2rpx solid #000;
			border-right: 2rpx solid #000;
			transform: rotateZ(135deg);
			margin-left: 20rpx;
			margin-top: -7rpx;
		}
		.screening-down-city-false{
			width: 20rpx;
			height: 20rpx;
			border-top: 2rpx solid #000;
			border-right: 2rpx solid #000;
			transform: rotateZ(-45deg);
			margin-left: 20rpx;
			margin-top: 10rpx;
		}
	}
	.screening-data{
		display: flex;
		flex-direction: row !important; 
		align-items: center;
		width: 32%;
		.screening-down{
			width: 20rpx;
			height: 20rpx;
			border-top: 2rpx solid #000;
			border-right: 2rpx solid #000;
			transform: rotateZ(135deg);
			margin-left: 20rpx;
			margin-top: -7rpx;
		}
		.screening-down-false{
			width: 20rpx;
			height: 20rpx;
			border-top: 2rpx solid #000;
			border-right: 2rpx solid #000;
			transform: rotateZ(-45deg);
			margin-left: 20rpx;
			margin-top: 10rpx;
		}
	}
}
</style>
